import os
import urllib.request
import cv2
import numpy as np

# 模型下载函数
def download_model(model_url, save_path):
    if not os.path.exists(save_path):
        os.makedirs(os.path.dirname(save_path), exist_ok=True)
        print(f"正在下载模型: {model_url}")
        urllib.request.urlretrieve(model_url, save_path)
        print(f"模型已保存到: {save_path}")
    else:
        print(f"模型已存在: {save_path}")

# 示例模型URL (替换为您实际需要的模型)
MODEL_URL = "https://github.com/opencv/opencv/raw/master/samples/dnn/face_detector/opencv_face_detector_uint8.pb"
CONFIG_URL = "https://github.com/opencv/opencv/raw/master/samples/dnn/face_detector/opencv_face_detector.pbtxt"

# 模型保存路径
MODEL_PATH = os.path.join(os.getcwd(), "model", "opencv_face_detector.pb")
CONFIG_PATH = os.path.join(os.getcwd(), "model", "opencv_face_detector.pbtxt")

# 下载模型
download_model(MODEL_URL, MODEL_PATH)
download_model(CONFIG_URL, CONFIG_PATH)

# 加载模型
net = cv2.dnn.readNetFromTensorflow(MODEL_PATH, CONFIG_PATH)
print("模型加载成功!")

# 示例使用函数
def detect_faces(image_path):
    # 读取图像
    frame = cv2.imread(image_path)
    if frame is None:
        print(f"无法读取图像: {image_path}")
        return

    # 准备输入
    blob = cv2.dnn.blobFromImage(frame, 1.0, (300, 300), [104, 117, 123], False, False)
    net.setInput(blob)
    
    # 推理
    detections = net.forward()
    
    # 处理结果
    for i in range(detections.shape[2]):
        confidence = detections[0, 0, i, 2]
        if confidence > 0.7:  # 置信度阈值
            print(f"检测到人脸，置信度: {confidence:.2f}")

# 示例使用
if __name__ == "__main__":
    # 替换为您的测试图像路径
    test_image = os.path.join(os.getcwd(), "test.jpg")
    detect_faces(test_image)